package com.next

import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured
import pl.touk.excel.export.WebXlsxExporter

import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.NOT_FOUND

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_HEAD_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_PRODUCT_MANAGER', 'ROLE_SECOND_BRANCH_OFFICE_PRODUCT_MANAGER',
    'ROLE_SECOND_BRANCH_OFFICE_DIRECTOR', 'ROLE_ACCOUNT_MANAGER', 'ROLE_SALES_REPRESENTATIVE', 'ROLE_BANK_OUTLETS_ADMINISTRATOR', 'ROLE_MERCHANT_ADMINISTRATOR', 'ROLE_CHANNEL_ADMINISTRATOR'])
@Transactional(readOnly = true)
class BocOpportunityTeamController
{

    def springSecurityService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = 10
        params.offset = params.offset ? params.offset.toInteger() : 0
        max = 10
        def offset = params.offset
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def sql = "from OpportunityTeam as o where 1=1"
        def opSql = "from Opportunity as a where 1=1"
        def list = []
        def count

        def serialNumber = params['serialNumber']
        def userFullName = params['user']
        def fullName = params['fullName']
        def idNumber = params['idNumber']
        def cellphone = params['cellphone']
        def startTime = params['startTime']
        def endTime = params['endTime']
        def channel = params['channel']
        def merchant = params['merchant']
        def status = params['status']

        if (serialNumber)
        {
            sql += " and o.opportunity.serialNumber like '%${serialNumber}%'"
            opSql += " and a.serialNumber like '%${serialNumber}%'"
        }
        if (fullName)
        {
            sql += " and o.opportunity.fullName like '%${fullName}%'"
            opSql += " and a.fullName like '%${fullName}%'"
        }
        if (idNumber)
        {
            sql += " and o.opportunity.idNumber like '%${idNumber}%'"
            opSql += " and a.idNumber like '%${idNumber}%'"
        }
        if (cellphone)
        {
            sql += " and o.opportunity.cellphone like '%${cellphone}%'"
            opSql += " and a.cellphone like '%${cellphone}%'"
        }
        if (startTime)
        {
            sql += " and o.opportunity.createdDate > '${startTime}'"
            opSql += " and a.startTime > '${startTime}'"
        }
        if (endTime)
        {
            sql += " and o.opportunity.createdDate < '%${endTime}%'"
            opSql += " and a.serialNumber < '%${endTime}%'"
        }

        if (channel)
        {
            sql += " and o.opportunity.account.parent.name like '%${channel}%'"
            opSql += " and a.account.parent.name like '%${channel}%'"
        }
        if (merchant)
        {
            sql += " and o.opportunity.account.name like '%${merchant}%'"
            opSql += " and a.account.name like '%${merchant}%'"
        }
        if (status)
        {
            sql += " and o.opportunity.status = '${status}'"
            opSql += " and a.status = '${status}'"
        }

        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            if (userFullName)
            {
                opSql += " and a.user.fullName like '%${userFullName}%'"
            }
            opSql += " order by modifiedDate desc"
            list = Opportunity.findAll(opSql, [max: max, offset: offset])
            count = Opportunity.executeQuery("select a.id " + opSql).size()
        }
        else
        {
            sql += " and o.user.id = ${user.id} order by modifiedDate desc"
            def buffer = OpportunityTeam.findAll(sql, [max: max, offset: offset])
            list = buffer?.opportunity

            count = OpportunityTeam.executeQuery("select o.id " + sql)?.size()
        }

        respond list, model: [opportunityTeamCount: count, params: params]
    }

    def create()
    {
        def opportunity = Opportunity.findById(params["opportunity"])
        if (opportunity?.status == "Pending")
        {
            def username = springSecurityService.getPrincipal().username
            def user = User.findByUsername(username)
            def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where user.id = ${user.id} and stage.instance.opportunity.id = ${opportunity.id} and stage.id = stage.instance.stage.id")
            if ((opportunityRole && opportunityRole?.authority?.name == "Approval") || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
            {
                def opportunityTeam = OpportunityTeam.findAllByOpportunity(opportunity)
                def userList
                def sqlStr = []
                opportunityTeam.each {
                    sqlStr.add(it.user.id)
                }
                userList = User.findAllByIdNotInList(sqlStr)
                respond new OpportunityTeam(params), model: [userList: userList, opportunity: opportunity]
            }
            else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
                return
            }
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    @Transactional
    def save(OpportunityTeam opportunityTeam)
    {
        if (opportunityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunityTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunityTeam.errors, view: 'create', model: [opportunity: opportunityTeam?.opportunity]
            return
        }

        Reporting[] reportingList = Reporting.findAllByUser(opportunityTeam.user)
        reportingList.each {
            User manager = it.manager
            OpportunityTeam ot = OpportunityTeam.findByOpportunityAndUser(opportunityTeam.opportunity, manager)
            if (!ot)
            {
                ot = new OpportunityTeam()
                ot.user = manager
                ot.opportunity = opportunityTeam.opportunity
                ot.save()
            }
        }

        opportunityTeam.save flush: true
        //添加edit权限
        // OpportunityRole opportunityRole = OpportunityRole.findByOpportunityAndUserAndStage(opportunityTeam
        //     .opportunity,
        //     opportunityTeam.user,
        //     opportunityTeam
        //         .opportunity.stage)
        // if (!opportunityRole)
        // {
        //     opportunityRole = new OpportunityRole()
        //     opportunityRole.opportunity = opportunityTeam?.opportunity
        //     opportunityRole.user = opportunityTeam?.user
        //     opportunityRole.stage = opportunityTeam?.opportunity?.stage
        //     opportunityRole.teamRole = TeamRole.findByName("Edit")
        //     opportunityRole.save flush: true
        // }

        // if (opportunityTeam.opportunity.stage.code == "04" && opportunityTeam.user.department.name in ["权证组",
        // "支持组", "风控组"])
        // {
        //     messageService.sendMessage2(CreditReportProvider.findByCode("PV")?.apiUrl,opportunityTeam.user.cellphone, "【Default】您好，有已报单订单（" + opportunityTeam
        // .opportunity.serialNumber + "）分配至您处，请及时处理！谢谢！")
        // }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: '', args: [message(code: 'opportunityTeam.label', default: 'OpportunityTeam'), opportunityTeam.id])
                // redirect(action: "show", id: opportunityTeam.opportunity.id)
                redirect(controller: "opportunity", action: "show", params: [id: opportunityTeam.opportunity.id])
            }
            '*' { respond opportunityTeam, [status: CREATED] }
        }
    }

    def edit(OpportunityTeam opportunityTeam)
    {
        respond opportunityTeam
    }

    @Transactional
    def update(OpportunityTeam opportunityTeam)
    {
        if (opportunityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunityTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunityTeam.errors, view: 'edit'
            return
        }
        opportunityTeam.save flush: true

        redirect opportunityTeam
    }

    @Transactional
    def delete(OpportunityTeam opportunityTeam)
    {
        if (opportunityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        opportunityTeam.delete flush: true

        // redirect(action: "show", id: opportunityTeam.opportunity.id)
        redirect(controller: "opportunity", action: "show", params: [id: opportunityTeam.opportunity.id])
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'opportunityTeam' + '.label', default: 'OpportunityTeam'),
                    params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

}
